package 滑动窗口;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhengTao
 * @version 1.0
 * @description: 水果成篮
 * @date 2022/10/14 17:27
 */
public class Demo904 {
    public static void main(String[] args) {
        int[] nums=new int[]{3,3,3,1,2,1,1,2,3,3,4};
        System.out.println(totalFruit(nums));
    }
    //超时
    public static int totalFruit(int[] fruits) {
        int res=Integer.MIN_VALUE;
        int j=0;   //起始位置
        int[] fruitsInts=new int[fruits.length];


        for (int i = 0; i < fruits.length; i++) {
               fruitsInts[fruits[i]]++;
               //水果数字小于2
               if (vaild(fruitsInts)){
                    res=Math.max(i-j+1,res);
               }
               while (!vaild(fruitsInts)){
                   fruitsInts[fruits[j++]]--;
               }
        }
     return  res;
    }
    //篮子中水果种类数
    private  static boolean vaild(int[] fruitsInts) {
        int sum=0;
        for (int fruitsInt : fruitsInts) {
            if(fruitsInt>0){
                sum++;
            }
        }
        return sum<3;
    }

    public static int totalFruit1(int[] fruits) {
        int res=Integer.MIN_VALUE;
        int j=0;   //起始位置
        HashMap<Integer,Integer> fruitsMap=new HashMap();
        for (int i = 0; i < fruits.length; i++) {
            fruitsMap.put(fruits[i], fruitsMap.getOrDefault(fruits[i],0)+1);
            //水果数字大于2
           while (fruitsMap.size()>2){
               fruitsMap.put(fruits[j],fruitsMap.get(fruits[j])-1);
               if(fruitsMap.get(fruits[j])==0){
                   fruitsMap.remove(fruits[j]);
               }
               //开始滑动
               j++;
           }
           res=Math.max(i-j+1,res);
        }
        return  res;
    }


}
